<?php

namespace app\db\controller;

use think\Db;
use app\common\controller\Frontend;

// class DbScript extends Frontend
class DbScript
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * 初始化系统模板-自定义
     * @author MSQ 2021-8-2
    **/
    public function initSystemTemplate()
    {
        # question_type 问题答案（填写）类型：1-单选题，2-多选题，3-下拉，4-附件上传，5-单行文本 6-多行文本 7-时间（Y-m-d）
        $data = [
            [
                'first_dir_name' => '基本信息',
                'dir_data' => [
                    [
                        'second_dir_name' => '基本信息',
                        'item_data' => [
                            [
                                'item_name' => '个人基本信息',
                                'item_data' => [
                                    [
                                        'item_name' => '个人基本信息',
                                        'question_data' => [
                                            [
                                                'question_name'   => 'QID',
                                                'question_type'   => '5',
                                                'question_option' => [],
                                                'question_data'   => [],
                                            ],[
                                                'question_name'   => '姓名',
                                                'question_type'   => '5',
                                                'question_option' => [],
                                                'question_data'   => [],
                                            ],[
                                                'question_name'   => '性别',
                                                'question_type'   => '3',
                                                'question_data'   => [],
                                                'question_option' => [
                                                    [
                                                        'option_name' => '男',
                                                        'is_other'    => 0
                                                    ],[
                                                        'option_name' => '女',
                                                        'is_other'    => 0
                                                    ]
                                                ]
                                            ],[
                                                'question_name'   => '出生日期',
                                                'question_type'   => '7',
                                                'question_option' => [],
                                                'question_data'   => [],
                                            ],
                                        ]
                                    ]
                                ]
                            ],[
                                'item_name' => '个人通讯信息',
                                'item_data' => [
                                    [
                                        'item_name' => '个人通讯信息',
                                        'question_data' => [
                                            [
                                                
                                                'question_name'   => '联系人',
                                                'question_type'   => '5',
                                                'question_option' => [],
                                                'question_data'   => [],
                                            ],[
                                                'question_name'   => '通讯地址',
                                                'question_type'   => '6',
                                                'question_option' => [],
                                                'question_data'   => [],
                                            ],
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ],[
                        'second_dir_name' => '住院和诊疗管理',
                        'item_data' => [
                            [
                                'item_name' => '住院信息',
                                'item_data' => [
                                    [
                                        'item_name' => '住院信息',
                                        'question_data' => [
                                            [
                                                'question_name'   => '门诊/入院诊断',
                                                'question_type'   => '0',
                                                'question_option' => [],
                                                'question_data'   => [
                                                    [
                                                        'question_name'   => '主要诊断',
                                                        'question_type'   => '1',
                                                        'question_data'   => [],
                                                        'question_option' => [
                                                            [
                                                                'option_name' => '支气管或肺肿物/结节',
                                                                'is_other'    => 0
                                                            ],[
                                                                'option_name' => '肺部空洞 ',
                                                                'is_other'    => 0
                                                            ],
                                                        ]
                                                    ],[
                                                        'question_name'   => '次要诊断',
                                                        'question_type'   => 2,
                                                        'question_data'   => [],
                                                        'question_option' => [
                                                            [
                                                                'option_name' => '支气管或肺肿物/结节',
                                                                'is_other'    => 0
                                                            ],[
                                                                'option_name' => '肺部空洞',
                                                                'is_other'    => 0
                                                            ],
                                                        ]
                                                    ],[
                                                        'question_name'   => '总体诊疗策略',
                                                        'question_type'   => 6,
                                                        'question_option' => [],
                                                        'question_data'   => [],
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                            
                        ]
                    ]
                ]
            ],[
                // 只有一级目录
                'first_dir_name' => '现病史',
                'dir_data' => [],
                'item_data' => [
                    [
                        'item_name' => '临床表现',
                        'item_data' => [
                            [
                                'item_name' => '临床表现',
                                'question_data' => [
                                    [
                                        'question_name'   => '有无症状',
                                        'question_type'   => '1',
                                        'question_data'   => [],
                                        'question_option' => [
                                            [
                                                'option_name' => '有',
                                                'is_other'    => 0
                                            ],[
                                                'option_name' => '无 ',
                                                'is_other'    => 0
                                            ],
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];
        $time = time();
        $templateModel = model('DbTemplate');
        $itemModel     = model('DbItem');
        $relationItemModel = model('DbTemplateRelationItem');

        Db::startTrans();
        # 新增模板
        $templateData = [
            'template_name' => '系统初始模板',
            'type'          => 3,
            'is_use'        => 1,
            'create_time'   => $time,
            'update_time'   => $time,
        ];
        $template_id = $templateModel->insertGetId($templateData);
        if (!$template_id) {
            Db::rollback();
            exit('失败');
        }
        # 新增一级目录
        foreach ($data as $firstDirK => $firstDirV) {
            $item_key = $itemModel->getItemKey();

            $firstDirData = [
                'template_id'   => $template_id,
                'item_name'     => $firstDirV['first_dir_name'],
                'item_key'      => $item_key,
                'type'          => 1,
                'classify_rank' => 1,
                'create_type'   => 0,
                'create_time'   => $time,
                'update_time'   => $time,
            ];
            $firstDirId = $itemModel->insertGetId($firstDirData);
            if (!$firstDirId) {
                Db::rollback();
                exit('失败');
            }
            # 同步新增模板关联
            $relationFirstDirData = [
                'template_id' => $template_id,
                'item_id'     => $firstDirId,
                'item_name'   => $firstDirV['first_dir_name'],
                'create_time' => $time,
                'update_time' => $time,
            ];
            $relationFirstDirId = $relationItemModel->insertGetId($relationFirstDirData);
            if (!$relationFirstDirId) {
                Db::rollback();
                exit('失败');
            }
            # 新增二级目录
            if ($firstDirV['dir_data']) {
                foreach ($firstDirV['dir_data'] as $secondDirK => $secondDirV) {
                    $item_key = $itemModel->getItemKey();

                    $secondDirData = [
                        'template_id'   => $template_id,
                        'item_name'      => $secondDirV['second_dir_name'],
                        'item_key'       => $item_key,
                        'parent_item_id' => $firstDirId,
                        'type'           => 1,
                        'classify_rank'  => 2,
                        'create_type'    => 0,
                        'create_time'    => $time,
                        'update_time'    => $time,
                    ];
                    $secondDirId = $itemModel->insertGetId($secondDirData);
                    if (!$secondDirId) {
                        Db::rollback();
                        exit('失败');
                    }
                    # 同步新增模板关联
                    $relationSecondDirData = [
                        'template_id' => $template_id,
                        'item_id'     => $secondDirId,
                        'item_name'   => $secondDirV['second_dir_name'],
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                    $relationSecondDirId = $relationItemModel->insertGetId($relationSecondDirData);
                    if (!$relationSecondDirId) {
                        Db::rollback();
                        exit('失败');
                    }

                    $itemRes = $this->initSystemTemplateCreateItem($template_id,$secondDirId,$secondDirV,$time);
                    if (!$itemRes) {
                        Db::rollback();
                        exit('失败');
                    }
                }
            }else{
                # 无二级目录
                $itemRes = $this->initSystemTemplateCreateItem($template_id,$firstDirId,$firstDirV,$time);
                if (!$itemRes) {
                    Db::rollback();
                    exit('失败');
                }
            }
        }
        dump(1);die;
        Db::commit();
        exit('成功');
    }
    /**
     * 初始化系统模板-创建item
     * @author MSQ 2021-8-2
    **/
    public function initSystemTemplateCreateItem($template_id = 0,$secondDirId = 0,$secondDirV = [],$time = 0)
    {
        $itemModel     = model('DbItem');
        $questionModel = model('DbQuestion');
        $optionModel   = model('DbQuestionOption');
        $relationItemModel     = model('DbTemplateRelationItem');
        $relationQuestionModel = model('DbTemplateRelationQuestion');
        $relationOptionModel   = model('DbTemplateRelationQuestionOption');
        # 新增一级模块
        foreach ($secondDirV['item_data'] as $firstItemK => $firstItemV) {
            $item_key = $itemModel->getItemKey();

            $firstItemData = [
                'template_id'    => $template_id,
                'item_name'      => $firstItemV['item_name'],
                'item_key'       => $item_key,
                'parent_item_id' => $secondDirId,
                'type'           => 2,
                'classify_rank'  => 1,
                'create_type'    => 0,
                'create_time'    => $time,
                'update_time'    => $time,
            ];
            $firstItemId = $itemModel->insertGetId($firstItemData);
            if (!$firstItemId) return false;
            # 同步新增模板关联
            $relationFirstItemData = [
                'template_id' => $template_id,
                'item_id'     => $firstItemId,
                'item_name'   => $firstItemV['item_name'],
                'create_time' => $time,
                'update_time' => $time,
            ];
            $relationFirstItemId = $relationItemModel->insertGetId($relationFirstItemData);
            if (!$relationFirstItemId) return false;

            # 新增二级模块
            foreach ($firstItemV['item_data'] as $itemK => $itemV) {
                $item_key = $itemModel->getItemKey();

                $itemData = [
                    'template_id'    => $template_id,
                    'item_name'      => $itemV['item_name'],
                    'item_key'       => $item_key,
                    'parent_item_id' => $firstItemId,
                    'type'           => 2,
                    'classify_rank'  => 2,
                    'create_type'    => 0,
                    'create_time'    => $time,
                    'update_time'    => $time,
                ];
                $itemId = $itemModel->insertGetId($itemData);
                if (!$itemId) return false;
                # 同步新增模板关联
                $relationItemData = [
                    'template_id' => $template_id,
                    'item_id'     => $itemId,
                    'item_name'   => $itemV['item_name'],
                    'create_time' => $time,
                    'update_time' => $time,
                ];
                $relationItemId = $relationItemModel->insertGetId($relationItemData);
                if (!$relationItemId) return false;

                # 新增一级变量
                foreach ($itemV['question_data'] as $questionK => $questionV) {
                    $question_key = $questionModel->getQuestionKey($questionV['question_name'],$item_key);

                    $questionGroupData = [
                        'template_id'       => $template_id,
                        'item_id'           => $itemId,
                        'question_name'     => $questionV['question_name'],
                        'question_key'      => $question_key,
                        'question_type'     => $questionV['question_type'],
                        'classify_rank'     => 1,
                        // 'question_unit'     => $questionV['question_unit'],
                        // 'input_placeholder' => $questionV['input_placeholder'],
                        'question_describe' => '系统生成',
                        'create_type'       => 0,
                        'create_time'       => $time,
                        'update_time'       => $time,
                    ];
                    $questionGroupId = $questionModel->insertGetId($questionGroupData);
                    if (!$questionGroupId) return false;
                    # 同步新增模板关联
                    $relationQuestionGroupData = [
                        'template_id'   => $template_id,
                        'item_id'       => $itemId,
                        'question_id'   => $questionGroupId,
                        'question_name' => $questionV['question_name'],
                        'create_time'   => $time,
                        'update_time'   => $time,
                    ];
                    $relationQuestionGroupId = $relationQuestionModel->insertGetId($relationQuestionGroupData);
                    if (!$relationQuestionGroupId) return false;

                    # 新增选项信息
                    foreach ($questionV['question_option'] as $optionK => $optionV) {

                        $option_key = $optionModel->getOptionKey();
                        $optionData = [
                            'template_id' => $template_id,
                            'option_name' => $optionV['option_name'],
                            'option_key'  => $option_key,
                            'question_id' => $questionGroupId,
                            'is_other'    => $optionV['is_other'],
                            'create_type' => 0,
                            'create_time' => $time,
                            'update_time' => $time,
                        ];
                        $option_id = $optionModel->insertGetId($optionData);
                        if (!$option_id) return false;
                        # 同步新增模板关联
                        $relationOptionData = [
                            'template_id' => $template_id,
                            'question_id' => $questionGroupId,
                            'option_id'   => $option_id,
                            'option_name' => $optionV['option_name'],
                            'create_time' => $time,
                            'update_time' => $time,
                        ];
                        $relationOptionId = $relationOptionModel->insertGetId($relationOptionData);
                        if (!$relationOptionId) return false;
                    }

                    # 新增二级变量
                    foreach ($questionV['question_data'] as $questionK2 => $questionV2) {
                        $question_key = $questionModel->getQuestionKey($questionV2['question_name'],$question_key);

                        $questionData = [
                            'template_id'       => $template_id,
                            'item_id'           => $itemId,
                            'parent_id'         => $questionGroupId,
                            'question_name'     => $questionV2['question_name'],
                            'question_key'      => $question_key,
                            'question_type'     => $questionV2['question_type'],
                            'classify_rank'     => 2,
                            // 'question_unit'     => $questionV['question_unit'],
                            // 'input_placeholder' => $questionV['input_placeholder'],
                            'question_describe' => '系统生成',
                            'create_type'       => 0,
                            'create_time'       => $time,
                            'update_time'       => $time,
                        ];
                        $questionId = $questionModel->insertGetId($questionData);
                        if (!$questionId) return false;
                        # 同步新增模板关联
                        $relationQuestionData = [
                            'template_id'   => $template_id,
                            'item_id'       => $itemId,
                            'question_id'   => $questionId,
                            'question_name' => $questionV2['question_name'],
                            'create_time'   => $time,
                            'update_time'   => $time,
                        ];
                        $relationQuestionId = $relationQuestionModel->insertGetId($relationQuestionData);
                        if (!$relationQuestionId) return false;

                        # 新增选项信息
                        foreach ($questionV2['question_option'] as $optionK2 => $optionV2) {
                            $option_key  = $optionModel->getOptionKey();
                            $optionData2 = [
                                'template_id' => $template_id,
                                'option_name' => $optionV2['option_name'],
                                'option_key'  => $option_key,
                                'question_id' => $questionId,
                                'is_other'    => $optionV2['is_other'],
                                'create_type' => 0,
                                'create_time' => $time,
                                'update_time' => $time,
                            ];
                            $option_id2 = $optionModel->insertGetId($optionData2);
                            if (!$option_id2) return false;
                            # 同步新增模板关联
                            $relationOptionData2 = [
                                'template_id' => $template_id,
                                'question_id' => $questionId,
                                'option_id'   => $option_id2,
                                'option_name' => $optionV2['option_name'],
                                'create_time' => $time,
                                'update_time' => $time,
                            ];
                            $relationOptionId2 = $relationOptionModel->insertGetId($relationOptionData2);
                            if (!$relationOptionId2) return false;
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * 初始化系统模板-同步肺二科
     * @author MSQ 2021-8-31
    **/
    public function initSystemTemplateNew()
    {
        // exit('接口已关闭');
        
        # 清空原本数据 谨慎操作！！！
        /*TRUNCATE TABLE qt_db_item;
        TRUNCATE TABLE qt_db_question;
        TRUNCATE TABLE qt_db_question_option;
        TRUNCATE TABLE qt_db_template_relation_item;
        TRUNCATE TABLE qt_db_template_relation_question;
        TRUNCATE TABLE qt_db_template_relation_question_option;*/
        # 初始化流程：
        # 同步系统     /index.php/db/DbScript/initSystemTemplateNew
        # 改创建类型   /index.php/db/DbScript/syncSaveCreateType
        # 同步基础模板 /index.php/db/DbScript/initBasicTemplate
        # 导出至标准版
        # 创建数据库

        $template_id = @model('DbTemplate')->getSysTemplateList()[0]['id'];
        if (!$template_id) exit('未找到系统模板');

        # 特殊变量key
        $filterQuestionKey[] = ['LIKE','history_past_diseases__cardiovascular_system%'];//心血管系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__digestive_system%'];//消化系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__blood_system%'];//血液系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__urinary_system%'];//泌尿系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__immune_system%'];//风湿、免疫系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__musculoskeletal_system%'];//肌肉骨骼系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__nervous_system%'];//神经系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__endocrine_system%'];//内分泌系统
        $filterQuestionKey[] = ['LIKE','history_past_diseases__respiratory_system%'];//呼吸系统
        $filterQuestionKey[] = ['LIKE','molecular_detection__pd_l1_or_pd_1_test_method%'];//PD-L1/PD-1检测方法
        $filterQuestionKey[] = 'OR';
        $filterQuestionWhere = [
            'q.delete_status'    => 0,
            'q.database_item_id' => ['IN','6,80'],
            'q.question_key'     => $filterQuestionKey,
        ];
        # 需要过滤的变量 特殊变量暂不同步
        # 触发性变量 既往疾病史和分子检测
        $filterQuestion = db('database_template_relation_question')->alias('r')
            ->join('database_question q','r.question_id=q.id')
            ->where($filterQuestionWhere)
            ->column('q.id');

        $time = time();
        Db::startTrans();

        $where = [
            'o.question_id'   => ['NOT IN',$filterQuestion],
            'o.option_status' => 1,
        ];
        # 需要同步的选项
        $optionList = db('database_template_relation_question_option')->alias('r')
            ->field('o.*,r.option_name option_name2,r.weight relation_weight,r.status show_status')
            ->join('database_question_option o','r.option_id=o.id')
            ->where($where)
            ->select();

        $optionList = array_chunk($optionList, 1000);
        foreach ($optionList as $key2 => $value2) {
            $addOption = $addRelationOption = [];
            foreach ($value2 as $key => $value) {
                $addOption[] = [
                    'id' => $value['id'],
                    'option_name' => $value['option_name'],
                    'option_key'  => $value['option_key'],
                    'question_id' => $value['question_id'],
                    'is_other'    => $value['is_other'],
                    'weight'      => $value['weight'],
                    'create_type' => $value['create_status'],
                    'create_time' => $time,
                    'update_time' => $time,
                ];

                $addRelationOption[] = [
                    'template_id' => $template_id,
                    'option_name' => $value['option_name2'],
                    'question_id' => $value['question_id'],
                    'option_id'   => $value['id'],
                    'weight'      => $value['relation_weight'],
                    'show_status' => $value['show_status'],
                    'create_time' => $time,
                    'update_time' => $time,
                ];
            }
            $res1 = Db::name('db_question_option')->insertAll($addOption);
            $res2 = Db::name('db_template_relation_question_option')->insertAll($addRelationOption);
            if (!$res1 || !$res2) {
                Db::rollback();
                exit('失败');
            }
        }
        $where = [
            'q.id' => ['NOT IN',$filterQuestion],
            'q.delete_status' => 0,
        ];
        # 需要同步的变量
        $questionList = db('database_template_relation_question')->alias('r')
            ->field('q.*,r.question_name question_name2,r.weight relation_weight,r.status show_status')
            ->join('database_question q','r.question_id=q.id')
            ->where($where)
            ->select();
        $questionList = array_chunk($questionList, 1000);
        foreach ($questionList as $key2 => $value2) {
            $addQuestion = $addRelationQuestion = [];
            foreach ($value2 as $key => $value) {
                # 新：问题答案（填写）类型：1-单选题，2-多选题，3-下拉，4-附件上传，5-单行文本 6-多行文本 7-时间（Y-m-d）
                
                # 旧：问题答案（填写）类型：1-单选题，2-多选题，3-自输入内容，4-附件上传，5-下拉列表，6-标签类型 答案输入类型，当question_type=3时，input_type 1-文本 2-多行文本 3-时间,6-多行文本【半行】
                
                switch ($value['question_type'])
                {
                    case 1:
                        $question_type = $value['question_type'];
                        break;  
                    case 2:
                        $question_type = $value['question_type'];
                        break;
                    case 3:
                        switch ($value['input_type'])
                        {
                            case 1:
                                $question_type = 5;
                                break;
                            case 2:
                                $question_type = 6;
                                break;
                            case 3:
                                $question_type = 7;
                                break;
                            case 6:
                                $question_type = 6;
                                break;
                            default:
                                $question_type = 0;
                                break;
                        }
                        break;
                    case 4:
                        $question_type = $value['question_type'];
                        break;
                    case 5:
                        $question_type = 3;
                        break;
                    default:
                        $question_type = 0;
                }
                $addQuestion[] = [
                    'id'                => $value['id'],
                    'item_id'           => $value['database_item_id'],
                    'question_name'     => $value['question_name'],
                    'question_key'      => $value['question_key'],
                    'question_type'     => $question_type,
                    'parent_id'         => $value['parent_id'],
                    'question_unit'     => $value['question_unit'],
                    'input_placeholder' => $value['input_placeholder'],
                    'question_describe' => $value['variable_describe'],
                    'weight'            => $value['weight'],
                    'create_type'       => $value['create_status'],
                    'create_time'       => $time,
                    'update_time'       => $time,
                ];

                $addRelationQuestion[] = [
                    'template_id'   => $template_id,
                    'item_id'       => $value['database_item_id'],
                    'question_name' => $value['question_name2'],
                    'question_id'   => $value['id'],
                    'weight'        => $value['relation_weight'],
                    'show_status'   => $value['show_status'],
                    'create_time'   => $time,
                    'update_time'   => $time,
                ];
            }
            $res1 = Db::name('db_question')->insertAll($addQuestion);
            $res2 = Db::name('db_template_relation_question')->insertAll($addRelationQuestion);
            if (!$res1 || !$res2) {
                Db::rollback();
                exit('失败');
            }
        }
        # 需要同步的模块/目录
        $itemList = db('database_template_relation_item')->alias('r')
            ->field('i.*,r.item_name item_name2,r.weight relation_weight,r.status show_status')
            ->join('database_item i','r.item_id=i.id')
            ->where(['i.delete_status' => 0])
            ->select();

        $itemList = array_chunk($itemList, 1000);
        foreach ($itemList as $key2 => $value2) {
            $addItem = $addRelationItem = [];
            foreach ($value2 as $key => $value) {
                $classify_rank = 1;
                if ($value['parent_item_id']) {
                    $parInfo = db('database_item')->where(['id' => $value['parent_item_id']])->find();
                    if ($parInfo['type'] == $value['type']) $classify_rank = 2;
                }
                $addItem[] = [
                    'id'            => $value['id'],
                    'classify_rank' => $classify_rank,
                    'item_name'     => $value['item_name'],
                    'item_key'      => $value['item_key'],
                    'type'          => $value['type'],
                    'parent_id'     => $value['parent_item_id'],
                    'weight'        => $value['weight'],
                    'create_type'   => $value['create_status'],
                    'create_time'   => $time,
                    'update_time'   => $time,
                ];
                $addRelationItem[] = [
                    'template_id' => $template_id,
                    'item_id'     => $value['id'],
                    'item_name'   => $value['item_name2'],
                    'weight'      => $value['relation_weight'],
                    'show_status' => $value['show_status'],
                    'create_time' => $time,
                    'update_time' => $time,
                ];
            }
            $res1 = Db::name('db_item')->insertAll($addItem);
            $res2 = Db::name('db_template_relation_item')->insertAll($addRelationItem);
            if (!$res1 || !$res2) {
                Db::rollback();
                exit('失败');
            }
        }
        Db::commit();
        exit('成功');
    }
    /**
     * 初始化基础模板-同步系统模板-同步肺二科
     * @author MSQ 2021-9-3
    **/
    public function initBasicTemplate()
    {
        // exit('接口已关闭');
        # 系统基础模板
        $template_id = @model('DbTemplate')->getSysBasicTemplateId()[0]['id'];      
        // 系统模板，即肺二科模板
        $origin_template_id = @model('DbTemplate')->getSysTemplateList()[0]['id'];
        $database_id = 0;
        $usercare_id = 0;

        $basicItem = model('DbItem')->getBasicDirChildItem();
        $basicItemIds = array_column($basicItem,'id');
        $relationItemData = [];
        Db::startTrans();

        # 递归引用目录&模块 从一级目录->二级模块
        # 调用前先去掉对应方法的database_id判断
        $res = model('DbTemplateRelationItem')->recursionSyncItemForQuoteTemplate($origin_template_id,$template_id,$database_id,$usercare_id,0,0,$basicItemIds,$relationItemData);
        if (!$res) {
            Db::rollback();
            exit('失败');
        }

        # 批量新增关联变量
        $relationItemData = array_chunk($relationItemData, 1000);
        foreach ($relationItemData as $key => $value) {
            model('DbTemplateRelationItem')->isUpdate(false)->saveAll($value);
        }
        Db::commit();
        # 用时9s
        exit('成功');
    }
    /**
     * 批量修改创建类型
     * 原系统模板几乎所有的都是系统创建，现只保留基础信息相关为系统创建，其他为自定义
     * 含目录&模块&变量
     * @author MSQ 2021-9-8
    **/
    public function syncSaveCreateType()
    {
        // exit('接口已关闭');
        
        # 基础信息相关目录/模块
        $basicItem = model('DbItem')->getBasicDirChildItem();
        $basicItemIds = array_column($basicItem,'id');
        
        $where = [
            'item_id'     => ['IN',$basicItemIds],
            'create_type' => 0
        ];
        # 基础信息相关变量
        $basicQuestionIds = model('DbQuestion')->customQuery($where);
        $basicQuestionIds = array_column($basicQuestionIds,'id');

        $where = [
            'question_id' => ['IN',$basicQuestionIds],
            'create_type' => 0
        ];
        # 基础信息相关选项
        $basicOptionIds = model('DbQuestionOption')->customQuery($where);
        $basicOptionIds = array_column($basicOptionIds,'id');
        
        $update = ['create_type' => 1];
        Db::startTrans();

        # 处理item表
        $where = [
            'id'          => ['NOT IN',$basicItemIds],
            'create_type' => 0
        ];
        $res = model('DbItem')->save($update,$where);
        if (!$res) {
            Db::rollback();
            exit('失败');
        }

        # 处理question表
        $where = [
            'id'          => ['NOT IN',$basicQuestionIds],
            'create_type' => 0
        ];
        $res = model('DbQuestion')->save($update,$where);
        if (!$res) {
            Db::rollback();
            exit('失败');
        }

        # 处理option表
        $where = [
            'id'          => ['NOT IN',$basicOptionIds],
            'create_type' => 0
        ];
        $res = model('DbQuestionOption')->save($update,$where);
        if (!$res) {
            Db::rollback();
            exit('失败');
        }
        Db::commit();

        exit('成功');
    }
    /**
     * 获取系统应该有但是并没有选项的变量
     * 避免设置模板时变量为单选/多选/下拉框但没有选项引起报错
     * @author MSQ 2021-9-9
    **/
    public function getNoOptionQuestionKey()
    {
        $where = [
            'question_type' => ['IN',[1,2,3]],
            'status'        => 1
        ];
        # 所有需要有选项的变量 单选、多选、下拉框
        $allNeedOptionQuestion = model('DbQuestion')->where($where)->column('id');

        $where = [
            'q.question_type' => ['IN',[1,2,3]],
            'q.status'        => 1
        ];
        # 所有有选项的变量 单选、多选、下拉框
        $hasOptionQuestion = model('DbQuestion')->alias('q')
            ->join('db_question_option o','o.question_id=q.id')
            ->where($where)
            ->group('q.id')
            ->column('q.id');
        # 取差集 即应该有但是并没有选项的变量
        $noOptionQuestion = array_diff($allNeedOptionQuestion,$hasOptionQuestion);

        # 没有选项变量的key
        $where = [
            'id'     => ['IN',$noOptionQuestion],
            'status' => 1,
            'question_key' => ['NOTLIKE','%&%'],
        ];
        $noOptionQuestionKey = model('DbQuestion')->where($where)->column('question_key');
        dump($noOptionQuestionKey);
    }
    /**
     * 获取系统重复选项的变量
     * 避免设置模板时变量为单选/多选/下拉框但有重复选项引起报错
     * @author MSQ 2021-10-9
    **/
    public function getRepeatOptionQuestion()
    {
        $where = [
            'status'      => 1,
            'template_id' => 0
        ];
        # 所有选项列表
        $allOptionList = db('db_question_option')->field('id,option_name,question_id')->where($where)->select();
        # 按变量id分组 question_id=>optionList
        $optionGroup = arrayGroupByKey($allOptionList,'question_id');
        $repeatData  = [];
        # 按选项分组循环
        foreach ($optionGroup as $key => $value) {
            # 该变量id下选项名称集合
            $optionName = array_column($value,'option_name');
            # 去重 个数是否相等
            $uniqueOptionName = array_unique($optionName);
            # 个数不同 记录重复
            if (count($optionName) != count($uniqueOptionName)) $repeatData[$key] = $value;
        }
        dump($repeatData);
        # 肺二科原系统是有三个变量选项重复
        # 1360 药物1给药途径 静脉泵入和局部用药
        # 1616 给药途径 静脉泵入
        # 1644 给药途径 静脉泵入
        # 重复变量均删除后面一个选项 即选项id为2432 2447 4457 4624
    }
}
